<?php

declare(strict_types=1);

namespace tmcore\base;

use think\Cache;
use think\facade\Cache as CacheStatic;

/**
 * 缓存基础类，用于管理缓存
 */
abstract class BaseCache extends Cache
{
    /**
     * 缓存标签(删除缓存时不删除，慎用)
     * @var string
     */
    public string $tagName = '';

    /**
     * 缓存前缀
     * @var string
     */
    public string $prefix = '';

    public function __construct()
    {
        parent::__construct(app());
    }

    /**
     * 缓存句柄
     * @return object
     */
    public function handler()
    {
        if($this->tagName) {
            return CacheStatic::tag($this->tagName);
        } else {
            return CacheStatic::store();
        }
    }

    /**
     * 重写set
     * @param string $key
     * @param mixed $value
     * @param mixed $ttl
     * @return bool
     */
    public function set($key, $value, $ttl = null): bool
    {
        return $this->handler()->set($this->prefix . $key, $value, $ttl);
    }

    /**
     * 重写get
     * @param string $key
     * @param mixed $default
     * @return mixed
     */
    public function get($key, $default = null):mixed
    {
        return $this->handler()->remember($this->prefix . $key, $default);
    }

    /**
     * 重写delete
     * @param string $key
     * @return bool
     */
    public function delete($key): bool
    {
        return CacheStatic::delete($this->prefix . $key);
    }

    /**
     * 重写has
     * @param string $key
     * @return bool
     */
    public function has($key): bool
    {
        return $this->handler()->has($this->prefix . $key);
    }

    /**
     * 重写inc
     * @param string $key
     * @param int $step
     * @return bool
     */
    public function inc($key, $step = 1)
    {
        return $this->handler()->inc($this->prefix . $key, $step);
    }

    /**
     * 重写dec
     * @param string $key
     * @param int $step
     * @return bool
     */
    public function dec( $key, $step = 1)
    {
        return $this->handler()->dec($this->prefix . $key, $step);
    }

    /**
     * 清除缓存类所有缓存
     * @return bool
     */
    public function deleteTag(): bool
    {
        return $this->tag($this->tagName)->clear();
    }

}